/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.Hash;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.TokenUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.SysToken;
import com.thinkgem.jeesite.modules.sys.service.SysTokenService;

/**
 * 系统token记录Controller
 * @author Jack
 * @version 2017-09-26
 */
@Controller
@RequestMapping(value = "/api/sysToken")
public class SysTokenController extends BaseController {
	
	@Autowired
	private SysTokenService sysTokenService;
	
	public static final String KEY_SHA = "SHA-256";
	
	public static final String CACHE_KEY_TOKEN = "cache_key_token_";
	
	@ModelAttribute
	public SysToken get(@RequestParam(required=false) String id) {
		SysToken entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sysTokenService.get(id);
		}
		if (entity == null){
			entity = new SysToken();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:sysToken:view")
	@RequestMapping(value = {"list", ""})
	public String list(SysToken sysToken, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SysToken> page = sysTokenService.findPage(new Page<SysToken>(request, response), sysToken); 
		model.addAttribute("page", page);
		return "modules/sys/sysTokenList";
	}

	@RequiresPermissions("sys:sysToken:view")
	@RequestMapping(value = "form")
	public String form(SysToken sysToken, Model model) {
		model.addAttribute("sysToken", sysToken);
		return "modules/sys/sysTokenForm";
	}

	@RequiresPermissions("sys:sysToken:edit")
	@RequestMapping(value = "save")
	public String save(SysToken sysToken, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, sysToken)){
			return form(sysToken, model);
		}
		sysTokenService.save(sysToken);
		addMessage(redirectAttributes, "保存系统token记录成功");
		return "redirect:"+Global.getAdminPath()+"/sys/sysToken/?repage";
	}
	
	@RequiresPermissions("sys:sysToken:edit")
	@RequestMapping(value = "delete")
	public String delete(SysToken sysToken, RedirectAttributes redirectAttributes) {
		sysTokenService.delete(sysToken);
		addMessage(redirectAttributes, "删除系统token记录成功");
		return "redirect:"+Global.getAdminPath()+"/sys/sysToken/?repage";
	}
	
	
	/**
	 * token的刷新、校验和分配
	 * @author Jack
	 * @date 2017年11月9日 下午2:04:15
	 * @description 
	 * @param token
	 * @return
	 * @throws UnsupportedEncodingException
	 *
	 */
	@RequestMapping(value = "tokenRefreshCheckAndAllot")
	public @ResponseBody String tokenMethod(SysToken token){
		String appid = token.getAppid();
		String secret = token.getSecret();
		List<SysToken> tokenList = sysTokenService.findList(new SysToken());
		//校验appid
		for(SysToken t : tokenList){
			if(t.getAppid().equals(appid) && t.getSecret().equals(secret)){
				//master校验appid和secret匹配
				//1、生成token信息写入master Cache
				Date createDate = DateUtils.parseDate(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
				String tmp = appid + secret  + createDate;
				String tokenResult =  Hash.sha1(tmp);
				CacheUtils.put(CACHE_KEY_TOKEN + appid, tokenResult);
				//2、将缓存返回到slaver请求结果中
				return tokenResult;
			}
		}
		return StringUtils.EMPTY;
	}
	
	@RequestMapping("/genToken")
	public @ResponseBody String genToken(@RequestParam(required=false, value="appid", defaultValue="")String appid,
			@RequestParam(required=false, value="secret", defaultValue="")String secret){
		if(StringUtils.isBlank(appid) || StringUtils.isBlank(secret)){
			return StringUtils.EMPTY;
		}
		List<SysToken> tokenList = sysTokenService.findList(new SysToken());
		//校验appid
		for(SysToken t : tokenList){
			if(t.getAppid().equals(appid) && t.getSecret().equals(secret)){
				//master校验appid和secret匹配
				//1、生成token信息写入master Cache
				Date createDate = DateUtils.parseDate(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//				String tmp = appid + secret  + createDate;
				String tmp = appid + secret;
				String tokenResult =  Hash.sha1(tmp);
				TokenUtils.saveToken(appid, tokenResult);
				//2、将缓存返回到slaver请求结果中
				return tokenResult;
			}
		}
		return StringUtils.EMPTY;
	}
	
	
}